package top.z.orm.handle.osql.autogen;

import top.z.orm.handle.osql.core.Logger;
import top.z.orm.handle.osql.util.StringUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.Map;

public class GenFiles {
    // 换行符
    private static final String LINE_SEPARATOR = System.getProperty("line.separator");

    private GenFiles() {
    }

    public static void genFile(String templatePath, Map<String, String> map, String targetFilePath) {
        genFile(templatePath, map, targetFilePath, "#{", "}");
    }

    public static void genFile(String templatePath, Map<String, String> map, String targetFilePath, String startToken, String endToken) {

        BufferedReader br        = null;
        StringBuffer   sb        = new StringBuffer();
        boolean        firstLine = true;
        try {
            br = FileUtil.readFile(templatePath);
            String temp = null;
            while ((temp = br.readLine()) != null) {
                temp = StringUtil.replaceWithMap(temp, map, startToken, endToken);
                if (firstLine) firstLine = false;
                else sb.append(LINE_SEPARATOR);
                sb.append(temp);
            }
            br.close();
        } catch (IOException e) {
            Logger.error(e.getMessage());
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException ioe) {
                    Logger.error(ioe.getMessage());
                }
            }
        }
//		FileUtil.genAppendFile(targetFilePath, sb.toString());
        FileUtil.genFile(targetFilePath, sb.toString());
    }
}
